package com.lanxin.oa.fiancial.service;

import com.lanxin.bean.*;
import com.lanxin.oa.approve.dao.NodeDao;
import com.lanxin.oa.fiancial.dao.ApplyDao;
import com.lanxin.util.PageBean;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ApplyServiceImpl implements ApplyService {
    @Autowired
    private ApplyDao applyDao;

    @Autowired
    private NodeDao nodeDao;


    @Override
    public PageBean<BxInformal> getDeptPage(HttpSession session, Integer page, Integer pageSize, BxInformal bxInformal) {
        return applyDao.selectBxInformalPage(session, page, pageSize, bxInformal);
    }

    @Override
    public List<BxInformaltype> selectBxType() {
        return applyDao.selectBxType();
    }


    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    //添加发送消息
    public void insertBxInformal(BxInformal bxInformal, HttpServletRequest request, MultipartFile[] content, Integer[] typeid, double[] applyAmount, String[] description, Integer[] detailoid, Integer[] accessaryoid, String[] contentfile, String[] dname) {
        if (bxInformal.getOid() == null) {
            SimpleDateFormat sim = new SimpleDateFormat("yyyyMMddhhmmssms");
            bxInformal.setDocNo("BXD" + sim.format(new Date()));
        }
        LcFlow lcFlow=applyDao.selectByIdLcFlow(bxInformal.getFlowid());
        bxInformal.setDocType(lcFlow.getDocType());
        ZzEmployee emp = applyDao.selectEmp(bxInformal.getProposer());
        bxInformal.setDeptid(emp.getDeptid());
        if (accessaryoid != null && !"".equals(accessaryoid)) {
            for (int i = 0; i < accessaryoid.length; i++) {
                BxInformalaccessary bx = new BxInformalaccessary();
                bx.setOid(accessaryoid[i]);
                bx.setContent(contentfile[i]);
                bx.setParentid(bxInformal.getOid());
                bx.setDescription(description[i]);
                bxInformal.getMalaccessary().add(bx);
            }
        }
        if (content != null && content.length > 0) {
            for (int i = 0; i < content.length; i++) {
                String str = upload(request, content[i]);
//                //用/进行切割
//                String[] spiltFileName = str.split("\\/");
//                //获取最后一个文件名
//                String lastName = spiltFileName[spiltFileName.length - 1];
                BxInformalaccessary bxInfor = new BxInformalaccessary();
                bxInfor.setContent(str);
                bxInfor.setParentid(bxInformal.getOid());
                bxInfor.setDescription(dname[i]);
                bxInformal.getMalaccessary().add(bxInfor);
            }
        }
        bxInformal.setCreateDate(new Date());
        bxInformal.setCreator((Integer) request.getSession().getAttribute("empid"));
        bxInformal.setStatus("W");
        double count = 0;
        if (typeid != null && typeid.length > 0) {
            for (int i = 0; i < typeid.length; i++) {
                BxInformaldetail bxInformaldetail = new BxInformaldetail();
                if(detailoid!=null && detailoid.length>0){
                    if(i<detailoid.length){
                        bxInformaldetail.setOid(detailoid[i]);
                    }
                }
                bxInformaldetail.setParentid(bxInformal.getOid());
                bxInformaldetail.setTypeid(typeid[i]);
                bxInformaldetail.setApplyAmount(applyAmount[i]);
                bxInformaldetail.setPlanid(bxInformal.getCreator());
                bxInformal.getMaldetails().add(bxInformaldetail);
                count = count + applyAmount[i];

            }
        }
        bxInformal.setApplyAmount(count);
        applyDao.saveOrUpdate(bxInformal);
    }

    @Override
    public BxInformal BxInFormalById(Integer oid) {
        return applyDao.selectByBxInFormalId(oid);
    }

    @Override
    public List<LcFlow> selectLcFlow() {
        return applyDao.selectLcFlow();
    }

    @Override
    public boolean updateBxStatus(Integer oid) {
        BxInformal bxInformal =applyDao.selectbx(oid);
        if (bxInformal != null && bxInformal.getMaldetails() != null && bxInformal.getMaldetails().size() > 0) {
            bxInformal.setStatus("S");
            bxInformal.setSubmitDate(new Date());
            applyDao.update(bxInformal);
            LcApproval lcApproval=new LcApproval();
            lcApproval.setOid(null);
            BeanUtils.copyProperties(bxInformal,lcApproval);
            lcApproval.setDocid(bxInformal.getOid());
            lcApproval.setNodeid(nodeDao.getFirstNode(lcApproval.getFlowid()).getOid());
            applyDao.add(lcApproval);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean deleteBxInformal(Integer oid) {
        BxInformal bxInformal = applyDao.deleteBxInformal(oid);
        if (bxInformal != null && bxInformal.getStatus().equals("W")) {
            applyDao.delete(bxInformal);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public PageBean<BxInformal> getbxinFormailPage(Integer page, Integer pageSize, BxInformal bxInformal, String empName) {
        return applyDao.listBxInformalPage(page, pageSize, bxInformal, empName);
    }

    @Override
    public PageBean<BxInformal> getregisterPage(Integer page, Integer pageSize, BxInformal bxInformal, String empName) {
        return applyDao.listregisterPage(page, pageSize, bxInformal, empName);
    }

    @Override
    public void updatePayeeInformal(BxInformal bxInformal, double[] amount, Integer[] doid) {
        BxInformal bx = applyDao.selectByBxInFormalId(bxInformal.getOid());
        bx.setBookDate(new Date());
        bx.setStatus("O");
        bx.setPayee(bxInformal.getPayee());
        bx.setBooker(bx.getPayee());
        //实报金额
        double Amouts = 0;
        Set<BxInformaldetail> set = new HashSet<>();
        for (int i = 0; i < doid.length; i++) {
            BxInformaldetail bxInformaldetail = (BxInformaldetail) applyDao.getById(BxInformaldetail.class, doid[i]);
            bxInformaldetail.setAmount(amount[i]);
            set.add(bxInformaldetail);
            Amouts = Amouts + amount[i];
        }
        bx.setMaldetails(set);
        bx.setBookAmount(Amouts);
        applyDao.update(bx);
    }
    //文件上传
    public String upload(HttpServletRequest request, MultipartFile content) {
        String str = "";
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replaceAll("-", "");
        String dir = request.getServletContext().getRealPath("upload");
        if (content.getSize() > 0) {
            File le = new File(dir + "/" + uuid);
            le.mkdir();
            str = uuid + "/" + content.getOriginalFilename();
            File newfile = new File(le, content.getOriginalFilename());
            try {
                FileUtils.copyInputStreamToFile(content.getInputStream(), newfile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return str;
    }

    //下载
    public void download(Integer oid, HttpServletResponse response,HttpServletRequest request){
        String dir=request.getServletContext().getRealPath("upload");
        BxInformalaccessary bx= (BxInformalaccessary) applyDao.getById(BxInformalaccessary.class,oid);
        String fileName=bx.getContent();
        File file=new File(dir+"/"+fileName);
        String str=fileName.substring(fileName.lastIndexOf("/")+1);
        try {
            str = URLEncoder.encode(str,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.reset();
        response.setHeader("Content-Disposition","attachment;filename=\""+str+"\"");
        response.addHeader("Content-Length",file.length()+"");
        response.setContentType("application/octet-stream;charset=utf-8");
        try {
            FileUtils.copyFile(file,response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //文件下载
    @Override
    public void xiazai(Integer oid, HttpServletResponse response, HttpServletRequest request) {
        if(oid!=null && !"".equals(oid)){
            download(oid,response,request);
        }
    }
}
